package com.scisoft.scan.util;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.scisoft.scan.db.LoginDBHelper;
import com.scisoft.scan.dy.LoginActivity;
import com.scisoft.scan.dy.UserInfo;
import com.scisoft.scan.ws.WebServiceHelper;

public class HeartBeatService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        int retVal = super.onStartCommand(intent, flags, startId);
        new PollingThread().start();
        return retVal;
    }

    private void returnToLogin() {
        HeartBeatUtil.stopPollingService(HeartBeatService.class);
        LoginDBHelper helper = new LoginDBHelper(getBaseContext(), "config.db", null, 1);
        helper.SetParm(LoginDBHelper.Parm_LoginState, "0");
        Intent intent = new Intent(getBaseContext(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(intent);
    }

    class PollingThread extends Thread {
        @Override
        public void run() {
            String checkAccount = "1";
            try {
                UserInfo userInfo = WebServiceHelper.AccountCheck();
                if (userInfo != null && "1".equals(userInfo.isValidate)) {
                    checkAccount = "1";
                } else {
                    checkAccount = "0";
                }
            } catch (Exception e) {
                checkAccount = "1";
            }
            if ("0".equals(checkAccount)) {
                returnToLogin();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
